package com.nightwalkbuddy.ui;

import com.nightwalkbuddy.dto.User;
import com.nightwalkbuddy.service.IUserService;
import com.nightwalkbuddy.service.UserServiceLive;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Login View page
 * 
 * FOR REVIEWER (case sensitive) username: peter password: pt11 OR GoTo
 * http://homepages.uc.edu/~liuhi/nightwalkSite/index.php to sign up account and
 * login with your credentials
 * 
 */
public class LoginActivity extends Activity {

	final static String CLASSNAME = "LoginActivity.java";
	final static String NOT_ONLINE = "No Internet connection. Activated offline login.";
	final static String NOT_OK = "NOTOK";
	final static String NOT_FOUND = "NOTFOUND";
	final static String LOGIN_ERROR = "ERROR";
	private EditText txtbox_username;
	private EditText txtbox_password;
	private Button btn_submit;
	private String aUsername;
	private String aPassword;
	private IUserService aUserService = new UserServiceLive();
	private String aEmTxtMsg;
	private String aEmPhoneNr;
	private User u = new User();
	boolean isConnected = false;
	private int alarm_selected = R.raw.alarm;
	private int spinnerPosition = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initComponents();
		try {
			ConnectivityManager cm = (ConnectivityManager) LoginActivity.this
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
			isConnected = activeNetwork.isConnected();
		} catch (NullPointerException e) {
			Log.v(this.toString(), NOT_ONLINE);
		}

		// popup(String.valueOf(isConnected));
	}

	/**
	 * LoginActivity components Connects to Website and check Login Credentials
	 * Fetch emergency contact info and text msg from Website Save user info to
	 * SQLite db for local use
	 */
	private void initComponents() {
		txtbox_username = (EditText) findViewById(R.id.txtbox_username);
		txtbox_password = (EditText) findViewById(R.id.txtbox_password);
		btn_submit = (Button) findViewById(R.id.btn_submit);

		btn_submit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// get username and password entries
				aUsername = txtbox_username.getText().toString().trim();
				aPassword = txtbox_password.getText().toString().trim();

				// validate input and authenticate
				if (aUsername.equals("") || aPassword.equals("")) {
					popup(getString(R.string.required_user_input));
				} else {
					if (isConnected == true) {
						try {
							String httpResponse = aUsername + "," + aPassword
									+ ",";
							String result = LOGIN_ERROR;
							try {
								result = aUserService.login(aUsername,
										aPassword);
								httpResponse += result;

								if (result.equalsIgnoreCase(NOT_OK)) {
									popup(getString(R.string.wrong_user_input));
								} else if (result.equalsIgnoreCase(LOGIN_ERROR)) {
									popup(getString(R.string.msg_login_error));
								} else if (result.equalsIgnoreCase(NOT_FOUND)) {
									popup(getString(R.string.user_not_found));
								} else {
									popup(getString(R.string.welcome_msg));
									aUserService.save(LoginActivity.this,
											httpResponse);
									u = aUserService.getUser(
											LoginActivity.this, aUsername);
									aEmPhoneNr = u.getEmPhoneNr();
									aEmTxtMsg = u.getEmMsg();
									getView(v);
								}

							} catch (IndexOutOfBoundsException e) {
								Log.e(CLASSNAME, e.toString());
							}
						} catch (NullPointerException e1) {
							e1.printStackTrace();
							Log.e(CLASSNAME, e1.toString());
						} catch (Exception e) {
							e.printStackTrace();
							Log.e(CLASSNAME, e.toString());
						}
					} else {
						boolean loginOK = false;
						// get user credential from SQLite db
						try {
							loginOK = aUserService.offlineLogin(
									LoginActivity.this, aUsername, aPassword);
							if (loginOK == true) {
								popup(getString(R.string.welcome_msg));
								u = aUserService.getUser(LoginActivity.this,
										aUsername);
								aEmPhoneNr = u.getEmPhoneNr();
								aEmTxtMsg = u.getEmMsg();
								getView(v);
							} else {
								popup(getString(R.string.wrong_user_input));
							}
						} catch (NullPointerException e) {
							Log.e(CLASSNAME, e.toString());
						} catch (Exception e) {
							Log.e(CLASSNAME, e.toString());
						}

					}

				}

				// clear text box entries
				txtbox_username.setText("");
				txtbox_password.setText("");
			}
		});
	}

	/**
	 * get username
	 * 
	 * @return the aUserName
	 */
	protected String getUsername() {
		return aUsername;
	}

	/**
	 * get user emergency text message
	 * 
	 * @return the aEmTxtMsg
	 */
	protected String getaEmTxtMsg() {
		return aEmTxtMsg;
	}

	/**
	 * get user emergency contact phone number
	 * 
	 * @return the aEmPhoneNr
	 */
	protected String getaEmPhoneNr() {
		return aEmPhoneNr;
	}

	/**
	 * get MenuActivity view for display
	 * 
	 * @param view
	 */
	protected void getView(View view) {
		Intent intent = new Intent(this, MenuActivity.class);
		intent.putExtra(getString(R.string.app_name), true);
		intent.putExtra("spinnerPosition", spinnerPosition);
		intent.putExtra("alarm_selected", alarm_selected);
		intent.putExtra("aUserName", this.getUsername());
		intent.putExtra("aMessage", this.getaEmTxtMsg());
		intent.putExtra("aPhoneNr", this.getaEmPhoneNr());
		intent.putExtra("sender", getString(R.string.title_activity_login));
		startActivity(intent);
	}

	/**
	 * pop up Toast message
	 * 
	 * @param message
	 *            the message
	 */
	protected void popup(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}
}
